'''
Created on Oct 13, 2012

@author: raygomez
'''
from AVP import AVP
from Error import InvalidAVPLengthError
from xdrlib import Packer, Unpacker

def _pack(avps):
    p = Packer()
    for a in avps:
        a.encode(p)
    return p.get_buffer()

class GroupedAVP(AVP):
    
    def __init__(self, code, avps=[], vendorId=0):
        AVP.__init__(self, code, _pack(avps), vendorId)
        
    def getAVPs(self):
        avps = []
        u = Unpacker(self.payload)
        bytesLeft = len(self.payload)
        while bytesLeft != 0:
            size = AVP.decodeSize(u, bytesLeft)
            if size == 0:
                raise InvalidAVPLengthError(self)
            a = AVP(1,"")
            a.decode(u, size)
            avps.append(a)
            bytesLeft -= size
        return avps
    
    def setAVPs(self, avps):
        self.payload = _pack(avps)
        
    def __str__(self):
        s = ""
        for a in self.getAVPs():
            if s!= "": s += ','
            s += a.str_prefix__()
        return str(self.code) + ":[" + s + "]"
    
    @staticmethod
    def convert(avp):
        avps = []
        u = Unpacker(avp.payload)
        bytesLeft = len(avp.payload)
        while bytesLeft > 0:
            size = AVP.decodeSize(u, bytesLeft)
            if size == 0:
                raise InvalidAVPLengthError(avp)
            a = AVP(1, "")
            a.decode(u, size)
            avps.append(a)
            bytesLeft -= size
        a = GroupedAVP(avp.code, avps, avp.vendorId)
        a.flags = avp.flags
        return a